﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceModel.Web;
using System.Text;
using Zeus.Comunicaciones.Utilidades.Serializer;

namespace Zeus.Comunicaciones.Utilidades.ConsumeService
{
    public class RestClient
    {
        protected string Content
        {
            get
            {
                string content;

                switch (Parameters.Count)
                {
                    case 0:
                        content = string.Empty;
                        break;
                    case 1:
                        content = CurrentSerialization.Serialize(Parameters.Single().Value);
                        break;
                    default:
                        content = CurrentSerialization.Serialize(Parameters);
                        break;
                }

                return content;
            }
        }

        public ISerializer CurrentSerialization
        {
            get
            {
                if (RequestFormat == WebMessageFormat.Json)
                {
                    return new JsonSerializer();
                }
                else
                {
                    return new XmlSerializer();
                }
            }
        }

        public string Method { get; set; }

        public string Uri { get; set; }

        public WebMessageFormat RequestFormat { get; set; }

        public WebMessageFormat ResponseFormat { get; set; }

        private Dictionary<string, object> parameters = new Dictionary<string, object>();

        public Dictionary<string, object> Parameters
        {
            get { return parameters; }
            set { parameters = value; }
        }

        private Dictionary<string, string> headersParameters = new Dictionary<string, string>();

        public Dictionary<string, string> HeadersParameters
        {
            get { return headersParameters; }
            set { headersParameters = value; }
        }

        protected string ContentType
        {
            get
            {
                return RequestFormat == WebMessageFormat.Json ? "text/json" : "text/xml";
            }
        }

        public void Invoke()
        {
            InvokeService();
        }

        public T InvokeAndGetResult<T>()
        {
            HttpWebResponse response = InvokeService();

            StreamReader responseStream = new StreamReader(response.GetResponseStream(), Encoding.UTF8);

            string data = responseStream.ReadToEnd();

            return CurrentSerialization.Deserialize<T>(data);
        }

        private HttpWebResponse InvokeService()
        {
            HttpWebRequest request = WebRequest.Create(Uri) as HttpWebRequest;
            request.KeepAlive = false;
            request.Method = Method.ToUpper();

            HeadersParameters.ToList().ForEach(t => request.Headers.Add(t.Key, t.Value));

            if (("POST,PUT").Split(',').Contains(Method.ToUpper()))
            {
                byte[] buffer = Encoding.UTF8.GetBytes(Content);
                request.ContentLength = buffer.Length;
                request.ContentType = ContentType;
                Stream postData = request.GetRequestStream();
                postData.Write(buffer, 0, buffer.Length);
                postData.Close();
            }

             return request.GetResponse() as HttpWebResponse;
        }
    }
}
